package cn.wolfcode.p2p.util;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.vo.VerifyCodeVO;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 用户上下文工具
 */
public class UserContext {
    //验证码
    public static final String VERIFYCODE_IN_SESSION = "verifycode_in_session";
    //用户
    public static final String LOGIN_IN_SESSION = "loginInfo";

    //获取request对象
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    //获取session对象
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    //获取ip
    public static String getIp() {
        return getRequest().getRemoteAddr();
    }

    /**
     * 设置验证码发送记录到session中
     *
     * @param codeVO
     */
    public static void setVerifycodeVO(VerifyCodeVO codeVO) {
        getSession().setAttribute(VERIFYCODE_IN_SESSION, codeVO);
    }

    /**
     * 获取session中的验证码记录
     * getSession()返回类型是object
     */
    public static VerifyCodeVO getVerifycodeVo() {
        return (VerifyCodeVO) getSession().getAttribute(VERIFYCODE_IN_SESSION);
    }

    //设置用户记录到session中
    public static void setLoginInfo(LoginInfo info) {
        getSession().setAttribute(LOGIN_IN_SESSION, info);
    }

    //获取用户
    public static LoginInfo getLoginInfo() {
        return (LoginInfo) getSession().getAttribute(LOGIN_IN_SESSION);
    }


}
